<template>
  <section class="page-container">
    <div class="toolbar">
      <span>选择角色:</span>
      <el-select v-model="role_id" size="small" placeholder="选择角色">
        <el-option
          v-for="item in roles"
          :key="item.id"
          :label="item.display_name"
          :value="item.id">
        </el-option>
      </el-select>
    </div>
    <el-transfer
      v-loading="loading"
      v-model="rolePermissions"
      filterable
      :titles="['权限列表', '拥有权限']"
      :props="{
        key: 'id',
        label: 'display_name'
      }"
      :data="permissions">
    </el-transfer>
    <div class="toolbar submit">
      <p><i class="el-icon-yuethink-information"></i> 权限设置不恰当，很可能会带来安全隐患。</p>
      <el-button type="success" size="small" icon="yuethink-save" @click="setPermissions" style="margin-left:30px;">保存权限</el-button>
      <el-button type="primary" size="small" icon="yuethink-refresh" @click="refresh">重新加载</el-button>
    </div>
  </section>
</template>
<script>
  import axios from 'axios'
  export default {
    data () {
      return {
        loading: false,
        roles: [],
        permissions: [],
        rolePermissions: [],
        role_id: ''
      }
    },
    watch: {
      role_id: {
        handler (newValue) {
          if (newValue) {
            this._getRolePermissions(`/roles/${newValue}/permissions`)
          }
        }
      }
    },
    mounted () {
      this._getData()
    },
    methods: {
      setPermissions () {
        if (!this.role_id) {
          this.$message.error('请选择角色')
          return false
        }
        this.$http.put(`/roles/${this.role_id}/permissions`, {permissions: this.rolePermissions})
        .then((response) => {
          this.$message.success('设置成功')
        }).catch((error) => {
          console.log(error)
        })
      },
      refresh () {
        location.reload()
      },
      _getPermissions () {
        return this.$http.get('/permissions?page_size=1000')
      },
      _getRolePermissions (url) {
        this.loading = true
        this.$http.get(url).then((response) => {
          this.loading = false
          this.rolePermissions = response.data
        }).catch((error) => {
          this.loading = false
          console.log(error)
        })
      },
      _getRoles () {
        return this.$http.get('/roles?page_size=1000')
      },
      _getData () {
        this.loading = true
        axios.all([this._getRoles(), this._getPermissions()])
        .then(axios.spread((roles, permissions) => {
          this.loading = false
          this.permissions = permissions.data.data
          this.roles = roles.data.data
          this.role_id = this.$route.query.role ? parseInt(this.$route.query.role) : ''
        })).catch((error) => {
          console.log(error)
          this.loading = false
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .el-transfer {
    margin: 10px 0;
  }
</style>